<template>
  <div class="weibo-card" v-if="postData">
    <div class="weibo-card__header">
      <img :src="'/img'+postData.tx" alt="avatar" class="weibo-card__avatar" />
      <div class="weibo-card__info">
        <span class="weibo-card__nickname">{{ postData.yhm }}</span>
        <span class="weibo-card__meta">{{ postData.time }} 来自 微博网页版</span>
        <div class="weibo-card__meta">
          标题# {{ postData.title }}
        </div>
      </div>
    </div>

    <div class="weibo-card__content">
      {{ postData.text }}
      <div class="weibo-card__image" v-if="postData.url && postData.url.trim()">
        <img  v-for="(imgUrl, index) in postData.url.split(',')"
              :key="index"
              :src="'/img'+imgUrl.trim()"
              alt="weibo-img"
              class="imgs"
        />
      </div>
    </div>

    <div class="weibo-card__actions">
      <span class="weibo-card__action" @click="showCommentBox = true">
        <el-icon><ChatDotRound /></el-icon>{{ commentList.length }}
      </span>
      <span class="weibo-card__action">
        <el-icon><StarFilled /></el-icon>{{ postData.likeCount || 0 }}
      </span>
      <span class="weibo-card__action">
        <el-icon><Share /></el-icon>{{ postData.forwardCount || 0 }}
      </span>
      <span class="weibo-card__action">
        <el-icon><View /></el-icon>{{ postData.browse || 0 }}
      </span>
    </div>

    <!-- 评论弹窗 -->
    <div class="comment-box" v-if="showCommentBox">
      <textarea
          v-model="commentContent"
          placeholder="写下你的评论..."
          class="comment-input"
          rows="3"
      ></textarea>
      <div class="comment-actions">
        <button class="cancel-btn" @click="showCommentBox = false">取消</button>
        <button class="send-btn" @click="sendComment">发送</button>
      </div>
    </div>

    <!-- 评论列表表格 -->
    <el-table
        :data="commentList"
        style="width: 100%"
        :row-class-name="tableRowClassName"
    >
      <el-table-column prop="avatar" width="180" />
      <el-table-column prop="nickname" width="180" />
      <el-table-column prop="commentContent" width="280" />
      <el-table-column prop="commentTime" />
      <!-- 新增：操作列（详情 + 删除） -->
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <!-- 详情按钮 -->
          <el-button type="text" @click="showCommentDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 评论详情弹窗 -->
    <el-dialog
        title="评论详情"
        v-model="dialogVisible"
        width="500px"
    >
      <div v-if="currentComment">
        <p><strong>评论人：</strong>{{ currentComment.nickname }}</p>
        <p><strong>内容：</strong>{{ currentComment.commentContent }}</p>
        <p><strong>时间：</strong>{{ currentComment.commentTime }}</p>
        <p><strong>头像：</strong><img :src="currentComment.avatar" style="width:60px; border-radius:50%;" /></p>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="danger" @click="deleteComment">删除评论</el-button>
      </template>
    </el-dialog>

  </div>

  <div v-else>加载中...</div>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ref, onMounted, computed } from 'vue';
import { ChatDotRound, StarFilled, Share, View } from '@element-plus/icons-vue';
import { useRoute } from 'vue-router';
import { ElDialog, ElButton } from 'element-plus'; // 引入 Element Plus 组件

// 帖子数据
const postData = ref<any>(null);
// 评论列表
const commentList = ref<any[]>([]);
// 评论弹窗控制
const showCommentBox = ref(false);
const commentContent = ref('');
// 路由参数
const route = useRoute();
const postId = route.query.id;

// 详情弹窗相关
const dialogVisible = ref(false);    // 弹窗显示状态
const currentComment = ref<any>({}); // 当前选中的评论数据

onMounted(() => {
  doList();   // 获取帖子详情
  doListp();  // 获取评论列表
});

/**
 * 获取帖子详情
 */
const doList = async () => {
  const { data } = await axios.get('/api/postAndUser/id/'+postId);
  postData.value = data;
};
/**
 * 获取评论列表
 */
const doListp = async () => {
  const { data } = await axios.get(`/api/commentp/${postId}`);
  commentList.value = data;
};

/**
 * 发送评论
 */
const sendComment = async () => {
  // 1. 校验内容
  if (!commentContent.value.trim()) {
    alert("评论内容不能为空！");
    return;
  }
  // 2. 获取必要参数
  const postId = postData.value?.id;
  const userId = localStorage.getItem("userId");
  if (!postId) {
    alert("未找到帖子信息，无法评论！");
    return;
  }
  // 3. 构造评论数据
  const comment = {
    postId: Number(postId),
    userId: userId ? Number(userId) : 1,
    text: commentContent.value,
    useredId: 0,
    url: null
  };
  try {
    await axios.post("/api/comment", comment);
    postData.value.commentCount = (postData.value.commentCount || 0) + 1;
    commentContent.value = "";
    showCommentBox.value = false;
    doListp();
    alert("评论发送成功！");
  } catch (error) {
    console.error("评论发送失败：", error);
    alert("评论发送失败，请重试！");
  }
};

/**
 * 显示评论详情
 */
const showCommentDetail = (comment: any) => {
  currentComment.value = comment;
  dialogVisible.value = true;
};

/**
 * 判断是否可删除（本人评论）
 */
const canDelete = (comment: any) => {
  const userId = localStorage.getItem('userId');
  if (!userId) return false;
  return Number(userId) === comment.userId;
};

/**
 * 删除评论
 */
const deleteComment = async (comment: any) => {
  // 新增：打印评论ID确认是否存在
  console.log('当前要删除的评论ID：', comment.id);
  try {
    await axios.delete(`/api/comment/${comment.id}`); // 假设后端接口：/api/comment/{id}
    doListp(); // 刷新评论列表
    dialogVisible.value = false; // 关闭弹窗
    alert('删除成功！');
  } catch (error) {
    console.error('删除失败：', error);
    alert('删除失败，请重试！');
  }
};


</script>

<style scoped>
.weibo-card {
  display: flex;
  height: auto;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.weibo-card__header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.weibo-card__avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 8px;
}
.weibo-card__info {
  display: flex;
  flex-direction: column;
}
.weibo-card__nickname {
  font-weight: bold;
  color: #333;
}
.weibo-card__meta {
  font-size: 12px;
  color: #999;
}
.weibo-card__content {
  margin: 8px 0;
  text-align: center;
  color: #333;
  line-height: 1.6;
}
.weibo-card__image {
  margin-top: 8px;
}
.weibo-card__image img {
  max-width: 200px;
  border-radius: 4px;
}
.weibo-card__actions {
  display: flex;
  gap: 24px;
  color: #666;
  margin-top: 8px;
  cursor: pointer;
  justify-content: center;
}
.weibo-card__action {
  display: flex;
  align-items: center;
  gap: 4px;
  transition: color 0.2s;
}
.weibo-card__action:hover {
  color: #409eff;
}

/* 评论框样式 */
.comment-box {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #eee;
}
.comment-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  font-size: 14px;
}
.comment-input:focus {
  outline: none;
  border-color: #409eff;
}
.comment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 8px;
}
.cancel-btn, .send-btn {
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}
.cancel-btn {
  border: 1px solid #ddd;
  background-color: #fff;
  color: #666;
}
.cancel-btn:hover {
  border-color: #ccc;
  background-color: #f5f5f5;
}
.send-btn {
  border: none;
  background-color: #409eff;
  color: #fff;
}
.send-btn:hover {
  background-color: #66b1ff;
}
.imgs{
  width: 133px;
  height: 133px;
  margin: 0 2px;
}

</style>